package org.topic.discount;

import org.topic.surpermarket.Product;
import org.topic.user.ShoopingCart;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 特定水果折扣策略
 */
public class FruitDiscount implements DiscountStrategy {

    private String fruitName;    // 打折的水果名称

    private double discountRate; // 折扣率

    public FruitDiscount(String fruitName, double discountRate) {
        if (discountRate <= 0 || discountRate > 1) {
            throw new IllegalArgumentException("折扣率必须在0到1之间");
        }
        this.fruitName = fruitName;
        this.discountRate = discountRate;
    }

    @Override
    public BigDecimal applyDiscount(BigDecimal subtotal, ShoopingCart cart) {
        BigDecimal discountAmount  = BigDecimal.ZERO;
        for (Map.Entry<Product, Integer> entry : cart.getItems().entrySet()) {
            Product product = entry.getKey();
            if (product.getName().equals(fruitName)) {
                Integer quantity = entry.getValue();
                // 计算该商品的折扣金额
                discountAmount = product.getPrice()
                        .multiply(new BigDecimal(quantity.toString()))
                        .multiply(new BigDecimal(String.valueOf(discountRate)));
            }
        }
        return subtotal.subtract(discountAmount);
    }
}
